#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("服务器！");

    //创建QTcpServer实例
    tcpServer = new QTcpServer(this);

    //绑定并监听端口号一定是初始化的最后一步
    //通过信号槽指定如何处理连接
    connect(tcpServer, &QTcpServer::newConnection, this, &Widget::processConnection);
    bool res = tcpServer->listen(QHostAddress::Any, 2333);
    if(!res)
    {
        QMessageBox::critical(this, "启动失败！", tcpServer->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    //通过tcpServer拿到socket对象，通过这个对象和客户端进行通信
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "] 客户端上线！";
    ui->listWidget->addItem(log);

    //通过信号槽来处理客户端发来请求的情况
    connect(clientSocket, &QTcpSocket::readyRead, this, [=](){
        //读取出请求数据，此处readall返回的是QByteArray 通过赋值转成QString
        QString request = clientSocket->readAll();
        //根据请求处理响应
        const QString& response = process(request);
        //响应写回客户端
        clientSocket->write(response.toUtf8());
        //把上述信息记录到日志中
        QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "]" + "req:" + request + "res:" + response;
        ui->listWidget->addItem(log);
    });

    //通过信号槽处理客户端断开连接的情况
    connect(clientSocket, &QTcpSocket::disconnected, this, [=](){
        //把断开连接的信息通过日志显示
        QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "] 客户端下线！";
        ui->listWidget->addItem(log);

        //手动释放clientSocket
        //不能直接delete，当前槽函数主要围绕着clientSocket进行操作
        //一旦delete就意味着其他逻辑无法使用clientSocket
        //必须保证delete是这个槽函数中最后一步，而且要保证delete肯定能执行到，不会被return/抛出异常给跳过
        //用deleteLater 更合适
        clientSocket->deleteLater();
        //这个操作不会立即销毁，而是告诉Qt，下一轮事件循环中，再进行上述销毁操作
        //因为槽函数都是在事件循环中=执行的，进入到下一轮循环意味着上一轮的循环肯定结束了，也意味着当前槽函数也一定执行完毕了

    });
}

//回显服务器
QString Widget::process(const QString request)
{
    return request;
}

